/*
 * Copyright 2018 Confluent Inc.
 *
 * Licensed under the Confluent Community License (the "License"); you may not use
 * this file except in compliance with the License.  You may obtain a copy of the
 * License at
 *
 * http://www.confluent.io/confluent-community-license
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations under the License.
 */

package io.confluent.ksql.rest.server;

import com.github.rvesse.airline.HelpOption;
import com.github.rvesse.airline.annotations.Arguments;
import com.github.rvesse.airline.annotations.Command;
import com.github.rvesse.airline.annotations.Option;
import com.github.rvesse.airline.annotations.restrictions.Once;
import com.github.rvesse.airline.annotations.restrictions.Required;
import io.confluent.ksql.rest.util.OptionsParser;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import javax.inject.Inject;

@Command(name = "server", description = "KSQL Cluster")
public class ServerOptions {

  static final String QUERIES_FILE_CONFIG = "ksql.queries.file";

  // Only here so that the help message generated by Help.help() is accurate
  @Inject
  public HelpOption<?> help;

  @SuppressWarnings("unused") // Accessed via reflection
  @Once
  @Required
  @Arguments(
      title = "config-file",
      description = "A file specifying configs for the KSQL Server, KSQL, "
          + "and its underlying Kafka Streams instance(s). Refer to KSQL "
          + "documentation for a list of available configs.")
  private String propertiesFile;

  @SuppressWarnings("unused") // Accessed via reflection
  @Option(
      name = "--queries-file",
      description = "Path to the query file on the local machine.")
  private String queriesFile;

  File getPropertiesFile() {
    return new File(propertiesFile);
  }

  Optional<String> getQueriesFile(final Map<String, String> properties) {
    if (queriesFile != null) {
      return Optional.of(queriesFile);
    }

    return Optional.ofNullable(properties.get(QUERIES_FILE_CONFIG));
  }

  public static ServerOptions parse(final String...args) throws IOException {
    return OptionsParser.parse(args, ServerOptions.class);
  }
}
